package com.gitee.qdbp.filling.biz;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.gitee.qdbp.able.beans.KeyString;
import com.gitee.qdbp.tools.utils.VerifyTools;

/**
 * 实体数据分组填充单一类型处理基础实现类<br>
 * options多个字段以逗号分隔, 默认的填充字段为源字段去掉Id/Code后缀, 加上Name<br>
 * -- createUser,updateUser<br>
 * -- 等于createUser-createUserName,updateUser-updateUserName<br>
 * 也可以自定义转换关系<br>
 * -- creatorId-createUser,updatorId-updateUser<br>
 *
 * @author zhaohuihua
 * @version 20210113
 */
public abstract class BaseEntityDataFillGroupValueService<T> extends BaseEntityDataFillFieldValueBasic {

    /** 获取分组类型 **/
    protected T getTargetGroupType(Map<String, Object> data) {
        return null;
    }

    /** 查找目标值 (key=sourceValue, value=targetValue) **/
    protected abstract Map<?, ?> findTargetValueMaps(T groupType, Collection<? extends Serializable> sourceValues);

    @Override
    public void fillFieldValue(Iterable<Map<String, Object>> list, String option) {
        List<KeyString> options = parseOptions(option);
        // 分组
        Map<T, List<Map<String, Object>>> groups = new HashMap<>();
        List<Map<String, Object>> defaultGroups = new ArrayList<>();
        for (Map<String, Object> item : list) {
            T groupType = getTargetGroupType(item);
            if (VerifyTools.isBlank(groupType)) {
                defaultGroups.add(item);
            } else {
                if (groups.containsKey(groupType)) {
                    groups.get(groupType).add(item);
                } else {
                    List<Map<String, Object>> items = new ArrayList<>();
                    items.add(item);
                    groups.put(groupType, items);
                }
            }
        }
        for (Map.Entry<T, List<Map<String, Object>>> entry : groups.entrySet()) {
            fillFieldValue(entry.getKey(), entry.getValue(), options);
        }
        if (!defaultGroups.isEmpty()) {
            fillFieldValue(null, defaultGroups, options);
        }
    }

    protected void fillFieldValue(T groupType, Iterable<Map<String, Object>> list, List<KeyString> options) {
        // # 收集需要填充的信息
        // key=sourceValue
        Map<? extends Serializable, List<DataFillor>> sourceMaps = collectFillInfos(list, options);
        if (sourceMaps == null || sourceMaps.isEmpty()) {
            return;
        }
        // # 根据sourceValue查询targetValue
        List<? extends Serializable> sourceValues = new ArrayList<>(sourceMaps.keySet()); // 复制副本以防修改
        // key=sourceValue, value=targetValue
        Map<?, ?> targetMaps = findTargetValueMaps(groupType, sourceValues);
        if (targetMaps == null || targetMaps.isEmpty()) {
            return;
        }
        // # 将targetValue填充至originalData
        fillValueToOriginalData(sourceMaps, targetMaps);
    }

}
